<template>
    <a-modal :keyboard="false" :maskClosable="false" title="病区信息" :open="visible" :width="550" :confirmLoading="loading" centered @ok="handleSubmit" @cancel="handleCancel">
        <a-form layout="vertical" ref="formRef" :model="modelRef" la>
            <a-row :gutter="16" type="flex" justify="start">
                <a-col :xs="12" :sm="12" :md="24">
                    <a-form-item
                        label="所属楼层"
                        name="buildingIds"
                        :rules="[
                            {
                                required: true,
                                message: '请选择所属楼层',
                                trigger: 'change',
                            },
                        ]"
                    >
                        <a-cascader
                            v-model:value="modelRef.buildingIds"
                            :options="dictData.buildTreeData"
                            :field-names="{
                                children: 'children',
                                label: 'name',
                                value: 'id',
                            }"
                            placeholder="选择所属楼层"
                            style="width: 100%"
                        />
                    </a-form-item>
                </a-col>
                <a-col :xs="12" :sm="12" :md="24">
                    <a-form-item
                        label="病区名称"
                        name="deptName"
                        :rules="[
                            {
                                required: true,
                                message: '请输入病区名称',
                            },
                        ]"
                    >
                        <a-input v-model:value="modelRef.deptName"></a-input>
                    </a-form-item>
                </a-col>
                <a-col :xs="12" :sm="12" :md="24">
                    <a-form-item
                        label="管理人员"
                        name="deptCharge"
                        :rules="[
                            {
                                required: true,
                                message: '请输入管理人员',
                            },
                        ]"
                    >
                        <a-input v-model:value="modelRef.deptCharge"></a-input>
                    </a-form-item>
                </a-col>
                <a-col :xs="12" :sm="12" :md="24">
                    <a-form-item
                        label="管理人员电话"
                        name="deptTel"
                        :rules="[
                            {
                                required: true,
                                message: '请输入管理人员电话',
                            },
                        ]"
                    >
                        <a-input v-model:value="modelRef.deptTel"></a-input>
                    </a-form-item>
                </a-col>
            </a-row>
        </a-form>
    </a-modal>
</template>

<script lang="ts">
    import type { PropType } from 'vue';
    import { defineComponent, reactive, ref, watchEffect, watch, computed } from 'vue';
    import { message } from 'ant-design-vue';
    import { cloneDeep, isUndefined } from 'lodash-es';
    import { getMedicalWasteTypeList } from '@/api/hospital/medical-waste';
    import { createMedicalBasicDepartment, updateMedicalBasicDepartment, getMedicalBasicDepartment } from '@/api/companion/ward';
    import { getMedicalBuildTree } from '@/api/list/department';

    export default defineComponent({
        props: {
            visible: {
                type: Boolean,
                required: true,
            },
            model: {
                type: Object as PropType<any | null>,
                default: () => null,
            },
        },
        emits: ['cancel', 'success'],
        setup(props, { emit }) {
            const loading = ref(false);
            const formRef = ref<any>(null);
            const defaultForm = {
                projectCode: '',
                buildingId: '',
                buildingIds: [],
                deptName: '',
                deptCharge: '',
                deptTel: '',
                collectSign: 0,
                collectRoomNo: 0,
                deliveryPickingSign: 0,
                deliveryArriveSign: 0,
            };
            const modelRef = reactive<any>(cloneDeep(defaultForm));
            // const rulesRef = reactive({
            //     buildingName: [{ required: true, message: '请选择名称' }],
            //     propertyType: [{ required: true, message: '请选择' }],
            //     deliveryType: [{ required: true, message: '请选择' }],
            // });
            // const { validateInfos, resetFields, validate } = Form.useForm(modelRef, rulesRef);
            const dictData = reactive<any>({});

            // 记录初始值
            const initValues = reactive({});

            const typeList: any = ref([]);
            watch(
                () => props.visible,
                () => {
                    Object.assign(initValues, cloneDeep(props.model));
                },
            );
            watchEffect(async () => {
                if (props.visible) {
                    getMedicalWasteTypeList({ name: '' }).then(res => {
                        typeList.value = res.data;
                    });
                    if (props.model) {
                        Object.assign(modelRef, props.model);

                        getMedicalBuildData();
                    }
                }
            });
            const getMedicalBuildData = () => {
                getMedicalBuildTree(props.model.projectCode).then(build => {
                    dictData.buildTreeData = build.data;
                    if (!isUndefined(modelRef.id)) {
                        getMedicalBasicDepartment(modelRef.id).then(res => {
                            Object.assign(modelRef, res.data);

                            dictData.buildTreeData.map(item => {
                                item.children.map(list => {
                                    if (list.id == modelRef.buildingId) {
                                        modelRef.buildingIds = [item.id, list.id];
                                    }
                                });
                            });
                        });
                    }
                });
            };

            const handleCancel = () => {
                formRef.value.resetFields();
                emit('cancel');
                Object.keys(modelRef).forEach(key => {
                    delete modelRef[key];
                });
                Object.assign(modelRef, cloneDeep(defaultForm));
            };

            const handleSubmit = async () => {
                formRef.value.validate().then(res => {
                    loading.value = true;
                    modelRef.buildingId = modelRef.buildingIds[modelRef.buildingIds.length - 1];
                    if (modelRef.medicalWasteId) {
                        modelRef.medicalWaste = typeList.value.find(item => item.id == modelRef.medicalWasteId).name;
                    }
                    (isUndefined(modelRef.id) ? createMedicalBasicDepartment : updateMedicalBasicDepartment)(modelRef)
                        .then(res => {
                            if (res.code == 200) {
                                message.success('操作成功');
                                emit('success');
                                handleCancel();
                            }
                        })
                        .finally(() => {
                            loading.value = false;
                        });
                });
            };
            return {
                typeList,
                loading,
                formRef,
                modelRef,

                handleSubmit,
                handleCancel,

                initValues,

                dictData,
            };
        },
        components: {},
    });
</script>
